import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:install_plugin_v2/install_plugin_v2.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import 'update_widget.dart';

/**
 * author：lx
 * date：2021-0126
 * descr：带进度文字的圆角进度条
 */
class TPUpdteWidget extends StatefulWidget {
 //编译名称
 final String? buildName;
 //编译包名
 final String? packageName;
 //编译数量
 final String? buildVersionNo;
 //升级版本
 final String? buildVersion;
 //升级大小
 final String? buildFileSize;
 //升级内容
 final String? buildUpdateDescription;
 //升级地址
 final String? url;
 //是否强制更新
  bool needForceUpdate;

 /// 标题文字的大小
 final double titleTextSize;
 /// 更新文字内容的大小
 final double contentTextSize;
 /// 按钮文字的大小
 final double buttonTextSize;
 /// 顶部图片
 final Widget? topImage;
 final Widget? closeImage;
 /// 拓展高度(适配顶部图片高度不一致的情况）
 final double extraHeight;
 /// 边框圆角大小
 final double radius;
 /// 主题颜色
 final Color themeColor;
 /// 更新事件
 final VoidCallback? onUpdate;
 /// 可忽略更新
 final bool enableIgnore;
 /// 更新事件
 final VoidCallback? onIgnore;
 /// 进度条的背景颜色
 final Color progressBackgroundColor;
 /// 更新事件
 final VoidCallback? onClose;
 /// 更新按钮内容
 final String updateButtonText;
 /// 忽略按钮内容
 final String ignoreButtonText;
 /// 对话框的宽度
 final double width;

 TPUpdteWidget(
     {
       Key? key,
       @required this.packageName,
       @required this.buildVersionNo,
       @required this.buildVersion,
       @required this.buildFileSize,
       @required this.buildUpdateDescription,
       @required this.url,
       this.buildName = '',
       this.needForceUpdate = false,
       this.titleTextSize = 16.0,
       this.contentTextSize = 14.0,
       this.buttonTextSize = 14.0,
       this.progressBackgroundColor = const Color(0xFFFFCDD2),
       this.topImage,
       this.closeImage,
       this.extraHeight = 5.0,
       this.radius = 4.0,
       this.themeColor = Colors.red,
       this.enableIgnore = false,
       this.onIgnore,
       this.updateButtonText = '更新',
       this.ignoreButtonText = '忽略此版本',
       this.onClose,
       this.onUpdate,
       this.width = 0.0,
     })
     : super(key: key);
 @override
 _TPUpdteWidgetState createState() => _TPUpdteWidgetState();
}

class _TPUpdteWidgetState extends State<TPUpdteWidget> {
 //下载id
 static String taskId = '';
 ReceivePort _port = ReceivePort();
 int progress=-1;
 bool isTapUpdate=false;

 @override
 void initState() {
   // TODO: implement initState
   super.initState();
   IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
   _port.listen((dynamic data) {
       String id = data[0];
       DownloadTaskStatus status = data[1];
       progress = data[2];
       setState((){ });
       // 当下载完成时，调用安装
       if (taskId == id && status == DownloadTaskStatus.complete) {
         if (status == DownloadTaskStatus.complete) {
           //关闭更新进度框
           _closeUpdateWidget();
           //安装下载完的apk
           _installApk();
         }
       }
   });
   FlutterDownloader.registerCallback(_downListener);
 }
 @override
 void dispose() {
   IsolateNameServer.removePortNameMapping('downloader_send_port');
   super.dispose();
 }
 static _downListener(id, status, progress) {
   //更新下载进度
   print('_downListener-->id=$id,status=$status,progress=$progress');
   final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;
   send.send([id, status, progress]);
 }

 /// 安装
  Future<Null> _installApk() async {
   try {
     final path = await _apkLocalPath();
     InstallPlugin.installApk(path + '/${(widget.buildName??'').isEmpty?'${widget.packageName}':widget.buildName}_${widget.buildVersion}.apk', '${widget.packageName}')
         .then((result) {
       print('install apk $result');
     }).catchError((error) {
       print('install apk error: $error');
     });
   } on PlatformException catch (_) {}
 }

 /// 获取存储路径
  Future<String> _apkLocalPath() async {
   //获取根目录地址
   final dir = await getExternalStorageDirectory();
   //自定义目录路径(可多级)
   String path = (dir?.path??'') + '/appUpdateDemo';
   var directory = await new Directory(path).create(recursive: true);
   return directory.path;
 }

 @override
 Widget build(BuildContext context) {
   print('UpdateWidget-->progress=$progress');
   return UpdateWidget(
       key: widget.key,
       width: widget.width,
       title: '是否升级到${widget.buildVersion}版本？',
       updateContent: '${widget.buildUpdateDescription}',
       // updateContent: '新版本大小:${(widget.buildFileSize??'0')}M\n${widget.buildUpdateDescription}',
       onUpdate: () => executeDownload(widget.url??''),
       titleTextSize: widget.titleTextSize,
       contentTextSize: widget.contentTextSize,
       buttonTextSize: widget.buttonTextSize,
       progress: progress*1.0/100,
       progressBackgroundColor: widget.progressBackgroundColor,
       topImage: widget.topImage,
       closeImage: widget.closeImage,
       extraHeight: widget.extraHeight,
       radius: widget.radius,
       themeColor: widget.themeColor,
       enableIgnore: widget.enableIgnore,
       onIgnore: widget.onIgnore,
       isForce: widget.needForceUpdate,
       updateButtonText: widget.updateButtonText,
       ignoreButtonText: widget.ignoreButtonText,
       onClose: () => _closeUpdateWidget(),
   );
 }

 Future<String> executeDownload(String url) async {
   bool isCheck=await _checkPermission();
   if(isCheck){
     widget.needForceUpdate=true;
     setState(() {});
     final path = await _apkLocalPath();
     File file =File(path+'/${(widget.buildName??'').isEmpty?'${widget.packageName}':widget.buildName}_${widget.buildVersion}.apk');
     if(file.existsSync()){
       //关闭更新进度框
       _closeUpdateWidget();
       //直接安装
       _installApk();
       return '';
     }
     //发起请求
     taskId = (await FlutterDownloader.enqueue(
         url: url,
         fileName: '${(widget.buildName??'').isEmpty?'${widget.packageName}':widget.buildName}_${widget.buildVersion}.apk',
         savedDir: path,
         showNotification: false,
         openFileFromNotification: false))!;
   }
   setState(() {});
   return taskId;
 }

 //检查权限如果没有则申请
 Future<bool> _checkPermission() async {
   // 先对所在平台进行判断
   if (Platform.isAndroid) {
     var request =await Permission.storage.request();
     if (await request.isGranted) {
       return true;
     } else {
       return false;
     }
   } else {
     return true;
   }
 }

 _closeUpdateWidget() {
   Navigator.pop(context);
 }
}
